package queuedemo;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 涛
 * Date: 2023-10-05
 * Time: 13:02
 */
public class MyLinkQueue {
    static class ListNode {
        public int val;
        public ListNode prev;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }
    //头结点和尾结点
    public ListNode head;
    public ListNode last;
    public int usedSize;//节点个数

    public boolean offer(int val) {
        ListNode node = new ListNode(val);
        //一个节点都没有
        if(this.head == null) {
            head = node;
            last = node;
        } else {
            last.next = node;
            node.prev = last;
            last = last.next;
        }
        usedSize++;
        return true;
    }

    public int poll() {
        //一个节点都没有
        if(this.head == null) {
            //抛异常
            throw new MyLinkQueueException("没有节点可以访问");
            //return -1;
        }
        //只有一个节点
        if(this.head.next == null) {
            int val = this.head.val;
            this.head = null;
            this.last = null;
            return val;
        }
        //多个节点
        int val = this.head.val;
        this.head = head.next;
        this.head.prev = null;
        return val;
    }

    public int peek() {
        //一个节点都没有
        if(this.head == null) {
            //抛异常
            throw new MyLinkQueueException("没有节点可以访问");
            //return -1;
        }
        int val = this.head.val;
        return val;
    }

    public boolean empty() {
        return this.head == null;
    }

    public int size() {
        return usedSize;
    }
}
